package net.wicp.tams.common.tracer.instrumentation.impl;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.google.common.io.Resources;

import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;

@Slf4j
public class EnhanceHttpServlet extends EnhanceSuperClass {

	public EnhanceHttpServlet(String className) {
		super(className, "javax.servlet.http.HttpServlet");
	}

	@Override
	public Result enhance(CtMethod methods, String newMethodName) {
		try {
			final String source = Resources.toString(
					Resources.getResource(getClass(), "/enhance/HttpServlet_service.javassist"),
					Charset.forName("utf-8"));
			pool.importPackage("java.util");
			pool.importPackage("java.math");
			pool.importPackage("org.slf4j.MDC");
			methods.setBody(source, "this", newMethodName);
			return Result.getSuc();
		} catch (Exception e) {
			log.error("", e);
			return Result.getError("增强方法时错误");
		}

	}

	@Override
	public List<CtMethod> findEnhanceMethods(CtClass cc) {
		try {
			CtClass request = pool.get("javax.servlet.http.HttpServletRequest");
			CtClass response = pool.get("javax.servlet.http.HttpServletResponse");
			CtMethod serviceMethod;
			try {
				serviceMethod = cc.getDeclaredMethod("service", new CtClass[] { request, response });
				List<CtMethod> ret = new ArrayList<>();
				ret.add(serviceMethod);
				return ret;
			} catch (NotFoundException e) {
				log.error("", e);
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return null;
	}
}
